//
//  TLS_MyPageVC.m
//  Travel_World
//
//  Created by lanou on 15/10/12.
//  Copyright © 2015年 TLS. All rights reserved.
//

#import "TLS_MyPageVC.h"
#import "RESideMenu.h"
#import "TLST_jokeCell.h"
#import "TLST_jokeModel.h"
#import "TLST_jokeFrameModel.h"
#import "TLST_movieModel.h"
#import "TLST_movieCell.h"
#import "TLSWebViewController.h"
#import "TLST_WebVC.h"
#import "MJRefresh.h"

@interface TLS_MyPageVC ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,TLST_movieCellDelegate,UMSocialUIDelegate>
@property (nonatomic, strong) UITableView *jokeTabelView;
@property (nonatomic, strong) NSMutableArray *jokeFrameModelArr;
@property (nonatomic, strong) UIScrollView *bigScrollView;
@property (nonatomic, strong) UISegmentedControl *segVC;

@property (nonatomic, strong) UITableView *movieTabelView;
@property (nonatomic, strong) NSMutableArray *movieModelArr;

@property(nonatomic, copy)NSString *maxtime;// 加载第几页
@property(nonatomic,assign)BOOL isUpLoading;// 是否上拉加载更多
@end

@implementation TLS_MyPageVC
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.jokeFrameModelArr = [NSMutableArray array];
        self.movieModelArr = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.segVC = [[UISegmentedControl alloc] initWithItems:@[@"段子",@"视频"]];
    self.segVC.frame = CGRectMake(0, 7, 100, 30);
    self.segVC.layer.cornerRadius = 15;
    self.segVC.layer.borderWidth = 1;
    self.segVC.layer.borderColor = [UIColor colorWithRed:0.050 green:0.404 blue:0.820 alpha:1.000].CGColor;
    self.segVC.layer.masksToBounds = YES;
    self.segVC.selectedSegmentIndex = 0;
    [self.segVC addTarget:self action:@selector(selectContent) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.segVC;
    NSDictionary *selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self.segVC setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor colorWithWhite:0.145 alpha:1.000]};
    [self.segVC setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-gengduo"] style:UIBarButtonItemStylePlain target:self action:@selector(presentRightMenuViewController:)];
    
    self.bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-49)];
    self.bigScrollView.contentSize = CGSizeMake(WIDTH*2, HEIGHT-49);
    self.bigScrollView.delegate = self;
    self.bigScrollView.pagingEnabled = YES;
    self.bigScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.bigScrollView];
    
    self.jokeTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-49) style:UITableViewStylePlain];
    self.jokeTabelView.delegate = self;
    self.jokeTabelView.dataSource = self;
    [self.bigScrollView addSubview:self.jokeTabelView];

    self.movieTabelView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, 0, WIDTH, HEIGHT-49) style:UITableViewStylePlain];//presentRightMenuViewController:
    self.movieTabelView.delegate = self;
    self.movieTabelView.dataSource = self;
    [self.bigScrollView addSubview:self.movieTabelView];
    
    self.maxtime = @"";
    [self addHeaderAndFooter];
    [self createDataWithPageNumber:self.maxtime];
    
    [self addHeader];
    [self createMovieDataWithNum:@1];

    NSLog(@"---%@",[NSString stringWithFormat:@"%ld",[self multipleWithNumber:100]]);
}
- (NSInteger)multipleWithNumber:(NSInteger)number {
    NSInteger result = 1;
    for (; number > 1; number--) {
        result = number * result;
    }
    
    return  result;
    
}
- (void)selectContent{
    self.bigScrollView.contentOffset = CGPointMake(self.segVC.selectedSegmentIndex * WIDTH, 0);
}
- (void)createDataWithPageNumber:(NSString *)maxtime
{
    if (self.isUpLoading == NO) {
        [self.jokeFrameModelArr removeAllObjects];
    }
    [QTAFNnetWorkTool getUrl:[NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=73524B41-B2E2-47A7-B7FD-F20ADEFBE5DA&c=data&client=iphone&from=ios&jbk=0&mac=&market=&maxtime=%@&openudid=4c65d5f4fc3ff9b36a159d32c4a1dd434041ab3f&page=0&per=20&sub_flag=1&type=29&udid=&ver=3.6",maxtime] body:nil hudSuperView:self.view result:QTJSON headerFile:nil success:^(id result) {
        NSMutableArray *jokeArr = [TLST_jokeModel baseModelByArr:result[@"list"]];
        for (TLST_jokeModel *jokeModel in jokeArr) {
            TLST_jokeFrameModel *frameModel = [[TLST_jokeFrameModel alloc] init];
            frameModel.jokeModel = jokeModel;
            [self.jokeFrameModelArr addObject:frameModel];
        }
        self.maxtime = result[@"info"][@"maxtime"];
        self.placeLabel.hidden = YES;
        [self.jokeTabelView reloadData];
        // 结束刷新
        [self.jokeTabelView headerEndRefreshing];
        [self.jokeTabelView footerEndRefreshing];
    }];
}
- (void)createMovieDataWithNum:(NSNumber *)number
{
    if (self.movieModelArr.count > 0) {
        [self.movieModelArr removeAllObjects];
    }
    NSString *urlStr = [NSString stringWithFormat:@"http://api.tudou.com/v6/video/search?app_key=90256538062520f9&format=json&kw=侣行&pageNo=%@&pageSize=100&orderBy=createTime",number];
    NSString *url;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        url = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    } else { // iOS9之前
        url = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    [QTAFNnetWorkTool getUrl:url body:nil hudSuperView:self.view result:QTJSON headerFile:nil success:^(id result) {
        self.movieModelArr = [TLST_movieModel baseModelByArr:result[@"results"]];
        self.placeLabel.hidden = YES;
        [self.movieTabelView reloadData];
        [self.movieTabelView headerEndRefreshing];
    }];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.jokeTabelView) {
        return self.jokeFrameModelArr.count;
    } else {
        return self.movieModelArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.jokeTabelView) {
        TLST_jokeCell *cell = [TLST_jokeCell cellWithTabelView:tableView];
        if (self.jokeFrameModelArr.count > indexPath.row) {
            cell.jokeFrameModel = self.jokeFrameModelArr[indexPath.row];
        }
        return cell;
    } else {
        TLST_movieCell *cell = [TLST_movieCell cellWithTableView:tableView];
        if (self.movieModelArr.count > indexPath.row) {
            cell.delegate = self;
            cell.movieModel = self.movieModelArr[indexPath.row];
        }
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.jokeTabelView && self.jokeFrameModelArr.count > indexPath.row) {
        TLST_jokeFrameModel *frameModel = self.jokeFrameModelArr[indexPath.row];
        return frameModel.cellHeight;
    }else{
        return WIDTH/2+155;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.jokeTabelView) {
        TLST_jokeFrameModel *frameModel = self.jokeFrameModelArr[indexPath.row];
        TLST_jokeModel *jokeModel = frameModel.jokeModel;
        [self shareActionWithText:jokeModel.text];
    }
}
#pragma mark scrollView delegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.segVC.selectedSegmentIndex = self.bigScrollView.contentOffset.x / WIDTH;
}
- (void)moviePlayWithUrl:(NSString *)url {
    NSLog(@"heheh");
    TLST_WebVC *webVC = [[TLST_WebVC alloc] init];
    webVC.urlStr = url;
    [self.navigationController pushViewController:webVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)shareActionWithText:(NSString *)text{
    //UMShareToSina,UMShareToQzone,
    NSArray *shareArr = [NSArray arrayWithObjects:UMShareToTencent,nil];
    //UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.shareIamge]]];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"56299019e0f55a05f2004b14"
                                      shareText:text
                                     shareImage:nil
                                shareToSnsNames:shareArr
                                       delegate:self];
}
- (void)addHeaderAndFooter {
    __block TLS_MyPageVC *myPageVC = self;
    
    // 添加下拉刷新头部控件
    [self.jokeTabelView addHeaderWithCallback:^{
        
        // 进入刷新状态就会回调这个Block
        myPageVC.maxtime = @"";
        myPageVC.isUpLoading = NO;//标记为下拉操作
        //重新请求数据
        [myPageVC createDataWithPageNumber:myPageVC.maxtime];
    }];
    
    // 添加上拉刷新尾部控件
    [self.jokeTabelView addFooterWithCallback:^{
        
        // 进入刷新状态就会回调这个Block
        //myPageVC.pageNumber++;
        myPageVC.isUpLoading = YES;//标记为上拉操作
        //请求更多数据
       [myPageVC createDataWithPageNumber:myPageVC.maxtime];
    }];
}
- (void)addHeader
{
    __block TLS_MyPageVC *myPageVC = self;
    
    // 添加下拉刷新头部控件
    [self.movieTabelView addHeaderWithCallback:^{
        
        [myPageVC createMovieDataWithNum:@1];
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
